package cn.itcast.bos.web.action.take_delivery;

import domain.take_delivery.Promotion;
import cn.itcast.bos.service.take_delivery.PromotionService;
import cn.itcast.bos.web.action.common.BaseAction;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.aspectj.util.FileUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@ParentPackage("json-default")
@Namespace("/")
@Controller
@Scope("prototype")
public class PromotionAction extends BaseAction<Promotion> {

    private File titleImgFile;
    private String titleImgFileFileName;

    public void setTitleImgFileFileName(String titleImgFileFileName) {
        this.titleImgFileFileName = titleImgFileFileName;
    }

    public void setTitleImgFile(File titleImgFile) {
        this.titleImgFile = titleImgFile;
    }
    @Autowired
    private PromotionService promotionService;

    @Action(value = "promotion_save",results = {@Result(name = "success",location = "./pages/take_delivery/promotion.html",type = "redirect")})
    public String save() throws IOException {
        //接收图片
        String savepath = ServletActionContext.getServletContext().getRealPath("/upload/");
        String url = ServletActionContext.getRequest().getContextPath()+"/upload/";
        //生成随机图片名
        UUID uuid = UUID.randomUUID();
        String etx = titleImgFileFileName.substring(titleImgFileFileName.lastIndexOf("."));
        String randomName=uuid+etx;
        //保存图片
        File diskFile = new File(savepath + "/" + randomName);
        FileUtil.copyFile(titleImgFile,diskFile);
        model.setTitleImg(ServletActionContext.getRequest().getContextPath()
                + "/upload/" + randomName);

        // 调用业务层，完成活动任务数据保存
        promotionService.save(model);
        return SUCCESS;
    }

    @Action(value = "promotion_pageQuery",results = {@Result(name = "success",type = "json")})
    public String pageQuery(){
        //构造分页查询参数
        Pageable pageable = new PageRequest(page - 1, rows);
        //调用业务层
        Page<Promotion> pageDate = promotionService.findPageDate(pageable);
        //压入值栈
        pushPageDataToValueStack(pageDate);
        return  SUCCESS;
    }
}
